package com.xzl.xep.web.interseptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.xzl.xep.exception.BusinessException;
import com.xzl.xep.exception.FormValidationException;

public class BusinessExceptionResolver implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception e) {
		// TODO Auto-generated method stub
		
		
		if( e instanceof FormValidationException){
			FormValidationException fe = (FormValidationException)e;
		
			if(fe.isToView()){
				ModelAndView model = new ModelAndView(fe.toView());
				model.addObject(WebConstants.FORM_ERROR, fe);
				return model;
			}
		}
		
		if(e instanceof BusinessException){
			BusinessException be = (BusinessException) e;
			String msg = be.getMessage();
			
			if(isAjaxRequest(request)){
				try {
					ajaxExceptionRetrun(response,msg) ;
				} catch (IOException e1) {
					
				}
			}
			
		}
		
		
		return null;
	}
	
	
	private boolean isAjaxRequest(HttpServletRequest request){
		String requestedWith = request.getHeader("x-requested-with");
		if (requestedWith != null && "XMLHttpRequest".equals(requestedWith)) {
			return true;
		} else {
			return false;
		}
	}
	
	private void ajaxExceptionRetrun(HttpServletResponse response,String msg) throws IOException{
		if (!response.isCommitted())
			response.reset();	
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter write = response.getWriter();
		write.write("{\"err\":\""+msg+"\"}");
		write.flush();
		write.close();
	}

}
